package com.yehui.algorithm.sword;

import java.util.ArrayList;
import java.util.List;

/**
 * 顺时针打印矩阵
 * Created by XuChunH on 2016/9/6.
 */
public class PrintMatrixClockwise {
    public static ArrayList<Integer> printMatrix(int [][] matrix) {
        if(matrix == null) {
            return null;
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        int rowNum = matrix.length;
        int columnNum = matrix[0].length;
        int num = (rowNum < columnNum ? rowNum : columnNum - 1) / 2 + 1;
        int j = 0;
        for(int  i = 0; i < num; i++) {
            for(j = i; j < columnNum - i; j++) {
                list.add(matrix[i][j]);
            }
            for(j = i + 1; j < rowNum - i; j++){
                list.add(matrix[j][columnNum - i - 1]);
            }
            for(j = columnNum - i - 2; j > i - 1 && (rowNum - i - 1 != i); j--) {
                list.add(matrix[rowNum - i - 1][j]);
            }
            for(j = rowNum - i - 2; j > i && (columnNum - i - 1 != i); j--) {
                list.add(matrix[j][i]);
            }
        }
        return list;
    }
}
